// pages/cart/cart.js
//获取应用实例
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // 结算板块适配高度
    settlementBottom: 48,
    // 返回顶部
    floorstatus: false,
    // 全选
    allChoose: false,
    // 购物车
    cart:[
      {id:1,title:'2015年飞天茅台',spec:'规格500ml',price:1000.00,img:'../../assets/img/hot1.png',count: 1,selected: true},
      {id:2,title:'2016年飞天茅台',spec:'规格500ml',price:1000.00,img:'../../assets/img/hot1.png',count: 1,selected: true},
      {id:3,title:'2017年飞天茅台',spec:'规格500ml',price:1000.00,img:'../../assets/img/hot1.png',count: 1,selected: true},
      {id:4,title:'2018年飞天茅台',spec:'规格500ml',price:1000.00,img:'../../assets/img/hot1.png',count: 1,selected: true},
    ],
    // 购物车列表数据
    carListData:[],
    // 是否有数据
    hasCarData:true,
    // 重新购买的商品id
    againGoodsId:[],
    // 商品列表
    goodsList: [],
    // 可下单商品数量
    isBuyLength: null,
    // 可操作商品数量
    isHandleLength: null,
    // 编辑与否
    delete: false,
    // 总价
    totalPrice: 0,
    // 总数量
    total: 0,
    // 分页
    pagination:{
      pageNum: 1,  //分页初始值，页号1
      pageSize: 10, //分页初始值，每页20条
      total: null
    },
    screen:{
      orderK: '',
      orderV: ''
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    // 获取购物车列表
    this.getcarListData();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let goodsIdArr = [];
    if(options.goods_id){
      goodsIdArr = JSON.parse(options.goods_id);
      this.setData({
        againGoodsId:goodsIdArr
      })
    }
    ;
    // 获取相关推荐商品列表
    this.getGoodsListData('',this.data.pagination,this.data.screen);
    let modelmes = wx.getStorageSync('modelmes');
    let newSettlementBottom = 48;
    if(modelmes.search('iPhone X') != -1){
      newSettlementBottom = 82;
    }
    this.setData({
      settlementBottom: newSettlementBottom
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let newPageNum = this.data.pagination.pageNum + 1;
    this.setData({
      'pagination.pageNum': newPageNum
    })
    this.getGoodsListData('',this.data.pagination,this.data.screen);
  },
  /**
   * 获取滚动条当前位置
   */
  onPageScroll: function (e) {
    if (e.scrollTop > 500) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取购物车列表数据
  getcarListData:function(){
    api.carList([]).then(res => {
      if(res.code == 0){
        if(res.data.data){
          this.handleCarGoodsStatus(res.data.data);
        }
      }
    })
  },
  // 购物车商品状态判断
  handleCarGoodsStatus:function(carListData){
    let isBuyLengthNew = 0;
    let isHandleLengthNew = 0;
    if(carListData.length > 0){
      carListData.forEach(item => {
        // 商品是否被删除(数据不存在):不显示
        if(item.goods){
          item.isShow = true;
          if(this.data.againGoodsId.indexOf(item.goods_id) != -1){
            item.selected = true;
          }else{
            item.selected = false;
          }
          isHandleLengthNew++;
          // 商品是否是单品
          if(item.sku){
            item.isSku = true;
            // 不是单品，是否可以下单
            if(item.key_name == item.sku.key_name && item.key_value == item.sku.key_value){
              // 是否可下单
              item.isBuy = true;
              // 是否可操作(选框)
              item.isBuyShow = true
              // 可下单商品数量
              isBuyLengthNew++;
            }else{
              item.isBuy = false;
              item.isBuyShow = false
            }
          }else{
            item.isSku = false;
            // 是单品，是否可以下单
            if(item.price == item.goods.shop_price){
              item.isBuy = true;
              item.isBuyShow = true
              isBuyLengthNew++;
            }else{
              item.isBuy = false;
              item.isBuyShow = false
            }
          }
        }else{
          item.isShow = false;
        }
      })
      this.setData({
        carListData: [...carListData],
        hasCarData: true,
        delete:false,
        allChoose: false,
        isBuyLength: isBuyLengthNew,
        isHandleLength: isHandleLengthNew,
      });
      // 计算总价和总量
      this.countTotal();
    }else{
      this.setData({
        carListData: [],
        allChoose: false,
        delete:false,
        hasCarData: false,
        isBuyLength: null,
        isHandleLength: null,
      });
    }
    
    // 打印购物车列表数据/可下单商品个数/可操作商品个数
    // console.log(carListData);
    // console.log(isBuyLengthNew);
    // console.log(isHandleLengthNew);
    
  },
  // 编辑/完成
  deleteHandle:function(){
    let carListData = this.data.carListData;
    if(this.data.delete){ // 完成
      this.setData({
        delete: false,
        allChoose: false
      })
      this.handleCarGoodsStatus(carListData);
    }else{ // 编辑
      carListData.forEach(item => {
        item.isBuyShow = true;
        item.selected = false;
      })
      this.setData({
        carListData,
        delete: true,
        allChoose: false
      })
    }
  },
  // 数量文本框
  numInput: function(e){
    let carListArr = this.data.carListData;
    let cartId = e.currentTarget.dataset.id;
    let value = e.detail.value.replace(/\D/g, '');
    carListArr.forEach((item,index) => {
      if(cartId == item.cart_id){
        if(value <= 0){
          value = 1;
        }
        item.goods_num = value;
      }
    })
    this.setData({
      carListData: carListArr
    })
  },
  // 数量文本框+
  plus: function(e){
    let carListArr = this.data.carListData;
    let cartId = e.currentTarget.dataset.id;
    carListArr.forEach((item,index) => {
      if(cartId == item.cart_id){
        // 库存判断
        if(item.isSku){
          if(item.goods_num >= item.sku.store_qty){
            wx.showToast({
              title: '抱歉，库存不足！',
            })
            return false;
          }
        }else{
          if(item.goods_num >= item.goods.store_qty){
            wx.showToast({
              title: '抱歉，库存不足！',
              icon: 'none'
            })
            return false;
          }
        }
        // 限购判断
        if(item.goods.purchase_sum != 0){
          if(item.goods_num > item.goods.purchase_sum){
            wx.showToast({
              title: '抱歉，该商品只能限购'+item.goods.purchase_sum+'件！',
            })
            return false;
          }
        }
        item.goods_num += 1;
        this.countgoodsNum(carListArr,item.cart_id,item.goods_num);
      }
    })
    // 计算总价和总量
    this.countTotal();
  },
  // 数量文本框-
  minus: function(e){
    let carListArr = this.data.carListData;
    let cartId = e.currentTarget.dataset.id;
    carListArr.forEach((item,index) => {
      if(cartId == item.cart_id){
        // 最小起购判断
        if(item.goods_num <= item.goods.least_sum){
          wx.showToast({
            title: '抱歉，该商品最少'+item.goods.least_sum+'件起购！',
            icon: 'none'
          })
          return false;
        }
        item.goods_num -= 1;
        this.countgoodsNum(carListArr,item.cart_id,item.goods_num);
      }
    })
    this.setData({
      carListData: carListArr
    })
    // 计算总价和总量
    this.countTotal();
  },
  // 购物车商品数量计算
  countgoodsNum:function(carListArr,carId,goodsNum){
    wx.showLoading({
      title: '加载中',
    })
    api.editCarNum(carId,goodsNum).then(res => {
      if(res.code == 0){
        this.setData({
          carListData: carListArr
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
      wx.hideLoading();
    })
  },
  // 全选
  allChoose:function(){
    let status = this.data.allChoose;
    let carListDataArr = this.data.carListData;
    if(status){ // 取消全选
      carListDataArr.forEach(item => {
        item.selected = false
      })
      this.setData({ 
        allChoose: false,
        carListData: carListDataArr
      })
    }else{ // 全选
      carListDataArr.forEach(item => {
        if(item.isBuy || item.isBuyShow){
          item.selected = true
        }
        
      })
      this.setData({
        allChoose: true,
        carListData: carListDataArr
      })
    }
    // 计算总价和总量
    this.countTotal();
  },
  // 商品单选
  choose:function(e){
    let carListDataArr = this.data.carListData;
    let cartId = e.currentTarget.dataset.id;
    let num = 0;
    carListDataArr.forEach(item => {
      if(cartId == item.cart_id && item.isBuyShow){
        if(item.selected){
          item.selected = false;
        }else{
          item.selected = true;
        }
      }
      if(item.selected){
        num++;
      }
    })
    // 是否要全选
    if(this.data.delete){ // 编辑状态
      if(num < this.data.isHandleLength){
        this.setData({
          allChoose:false,
          carListData: carListDataArr
        })
      }else{
        this.setData({
          allChoose:true,
          carListData: carListDataArr
        })
      }
    }else{ // 非编辑状态
      if(num < this.data.isBuyLength){
        this.setData({
          allChoose:false,
          carListData: carListDataArr
        })
      }else{
        this.setData({
          allChoose:true,
          carListData: carListDataArr
        })
      }
      // 计算总价和总量
      this.countTotal();
    }
    
  },
  // 计算总价
  countTotal:function(){
    let carListDataArr = this.data.carListData;
    let totalPrice = 0;
    let total = 0;
    carListDataArr.forEach(item => {
      if(item.goods){
        // 已选并可下单
        if(item.selected&&item.isBuy){
          if(item.isSku){ // 非单品价格
            totalPrice += item.sku.price*item.goods_num;
          }else{ // 单品价格
            totalPrice += item.goods.shop_price*item.goods_num;
          }
          total += item.goods_num;
        }
      }
      
    })
    this.setData({
      totalPrice,
      total
    })
  },
  // 删除购物车商品
  deleteCar:function(e){
    let carId = e.currentTarget.dataset.id;
    let carListData = this.data.carListData;
    let carIdArr = [];
    if(carId){
      carIdArr.push(carId);
    }else{
      carListData.forEach(item => {
        if(item.selected){
          carIdArr.push(item.cart_id)
        }
      })
    }
    if(carIdArr.length > 0){
      api.deleteToCart(carIdArr).then(res => {
        if(res.code == 0){
          this.getcarListData();
        }
        wx.showToast({
          title: res.msg,
        })
      })
    }else{
      wx.showToast({
        title: '请选择商品',
      })
    }

  },
  // 获取商品列表数据
  getGoodsListData:function(keyword,pagiantion,screen){
    let goodsListArr = this.data.goodsList;
    // 数据已经到底
    if( goodsListArr.length == this.data.pagination.total){
      wx.showToast({
        title: '已经没有了~',
        icon: 'none',
        duration: 1500
      })
    }else{
      api.search(keyword,pagiantion,screen).then(res => {
        if(res.code == 0){
          if(res.data.total != 0){
            goodsListArr.push(...res.data.list);
            this.setData({
              goodsList: goodsListArr,
              'pagination.total': res.data.total
            })
          }else{
            this.setData({
              noDataNotice: keyword,
              noDataNoticeStatus: true
            })
            this.getGoodsListData('',pagiantion);
          }
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          })
        }
      })
    }
  },
  // 点击商品跳转到商品详情页
  jumpToGoods:function(e){
    let goodsId = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: '/pages/goods/goods?goods_id='+goodsId
    })
  },
  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  // 跳转到支付页面
  jumpToPay:function(){
    let orderGoods = [];
    let carListDataArr = this.data.carListData;
    carListDataArr.forEach(item => {
      if(item.isBuy && item.selected){
        orderGoods.push(item.cart_id);
      }
    })
    if(orderGoods.length > 0){
      wx.navigateTo({
        url: `/pages/pay/pay?orderGoods=${JSON.stringify(orderGoods)}`
      })
    }else{
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 1500
      })
    }
  }
})